'use client';

import { useState } from 'react';
import { 
  Calendar, 
  Bell, 
  Image as ImageIcon, 
  Plus, 
  Search,
  Filter,
  MoreHorizontal
} from 'lucide-react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { FadeIn } from '@/components/ui/motion';
import { useToast } from '@/components/ui/use-toast';
import { Toaster } from 'sonner';
import { useAuth } from '@/hooks/use-auth';
import { UserRole } from '@/types';

// 模拟数据
const mockNotices = [
  {
    id: 1,
    title: '期中考试安排通知',
    content: '各位同学，期中考试将于下周一至周三进行，请做好复习准备。考试科目包括语文、数学、英语、科学。请带好考试用具，不要迟到。',
    type: '考试通知',
    date: '2023-10-15',
    author: '王老师',
    important: true
  },
  {
    id: 2,
    title: '家长会通知',
    content: '定于10月25日下午3点在教室举行本学期家长会，请各位家长准时参加。会议内容包括：学生在校表现、学习情况反馈、家校合作事项讨论等。',
    type: '家长通知',
    date: '2023-10-10',
    author: '王老师',
    important: true
  },
  {
    id: 3,
    title: '课外阅读书目推荐',
    content: '为丰富同学们的课外阅读，现推荐以下书目：《窗边的小豆豆》、《夏洛的网》、《小王子》等。这些书籍有助于培养阅读习惯和提高语文素养。',
    type: '学习资料',
    date: '2023-10-05',
    author: '李老师',
    important: false
  },
  {
    id: 4,
    title: '卫生值日安排调整',
    content: '因近期活动安排，下周的卫生值日表有所调整，请各小组负责人查看班级公告栏的新值日表，并通知组内成员。',
    type: '日常通知',
    date: '2023-10-01',
    author: '王老师',
    important: false
  }
];

const mockActivities = [
  {
    id: 1,
    title: '班级秋游活动',
    content: '今天我们班级组织了秋游活动，同学们在植物园度过了愉快的一天。大家观察了各种植物，学习了植物知识，还进行了团队合作游戏，增进了同学间的友谊。',
    date: '2023-10-20',
    author: '王老师',
    images: [
      '/images/activity1-1.jpg',
      '/images/activity1-2.jpg',
      '/images/activity1-3.jpg'
    ],
    likes: 45,
    comments: 12
  },
  {
    id: 2,
    title: '科学实验课',
    content: '今天的科学课上，同学们进行了有趣的"水的净化"实验。通过这个实验，大家学习了水的过滤和净化原理，了解了保护水资源的重要性。同学们都表现得非常积极！',
    date: '2023-10-15',
    author: '张老师',
    images: [
      '/images/activity2-1.jpg',
      '/images/activity2-2.jpg'
    ],
    likes: 38,
    comments: 8
  },
  {
    id: 3,
    title: '班级读书分享会',
    content: '本周五下午，我们举行了班级读书分享会。同学们分享了自己最近阅读的书籍和心得体会。通过这样的活动，不仅培养了阅读兴趣，也锻炼了同学们的表达能力和自信心。',
    date: '2023-10-10',
    author: '王老师',
    images: [
      '/images/activity3-1.jpg'
    ],
    likes: 32,
    comments: 15
  }
];

// 模拟图片数据（实际项目中应该使用真实图片）
const mockImageUrls = {
  '/images/activity1-1.jpg': 'https://images.unsplash.com/photo-1571210862729-78a52d3779a2?q=80&w=1470&auto=format&fit=crop',
  '/images/activity1-2.jpg': 'https://images.unsplash.com/photo-1540479859555-17af45c78602?q=80&w=1470&auto=format&fit=crop',
  '/images/activity1-3.jpg': 'https://images.unsplash.com/photo-1588072432836-e10032774350?q=80&w=1472&auto=format&fit=crop',
  '/images/activity2-1.jpg': 'https://images.unsplash.com/photo-1427504494785-3a9ca7044f45?q=80&w=1470&auto=format&fit=crop',
  '/images/activity2-2.jpg': 'https://images.unsplash.com/photo-1509062522246-3755977927d7?q=80&w=1464&auto=format&fit=crop',
  '/images/activity3-1.jpg': 'https://images.unsplash.com/photo-1456513080510-7bf3a84b82f8?q=80&w=1373&auto=format&fit=crop'
};

export default function ClassActivitiesPage() {
  const { toast } = useToast();
  const { user } = useAuth();
  const isTeacher = user?.role === UserRole.TEACHER;
  const [activeTab, setActiveTab] = useState('activities');
  const [searchTerm, setSearchTerm] = useState('');
  const [noticeDialogOpen, setNoticeDialogOpen] = useState(false);
  const [activityDialogOpen, setActivityDialogOpen] = useState(false);
  const [selectedImages, setSelectedImages] = useState<string[]>([]);
  const [activities, setActivities] = useState(mockActivities);
  const [notices, setNotices] = useState(mockNotices);
  
  // 新建活动表单状态
  const [activityForm, setActivityForm] = useState({
    title: '',
    content: '',
  });

  // 新建通知表单状态
  const [noticeForm, setNoticeForm] = useState({
    title: '',
    content: '',
    type: '',
    important: false
  });

  // 处理活动表单变化
  const handleActivityFormChange = (field: string, value: string) => {
    setActivityForm(prev => ({
      ...prev,
      [field]: value
    }));
  };

  // 处理通知表单变化
  const handleNoticeFormChange = (field: string, value: string | boolean) => {
    setNoticeForm(prev => ({
      ...prev,
      [field]: value
    }));
  };

  // 模拟图片选择功能
  const handleImageSelect = () => {
    // 实际项目中应该使用文件上传组件
    const newImage = Object.keys(mockImageUrls)[Math.floor(Math.random() * Object.keys(mockImageUrls).length)];
    setSelectedImages(prev => [...prev, newImage]);
  };

  // 发布活动
  const handlePublishActivity = () => {
    if (!activityForm.title || !activityForm.content || selectedImages.length === 0) {
      toast({
        title: "请完善活动信息",
        description: "标题、内容和照片都是必填项",
        variant: "destructive"
      });
      return;
    }

    const newActivity = {
      id: activities.length + 1,
      title: activityForm.title,
      content: activityForm.content,
      date: new Date().toISOString().split('T')[0],
      author: '王老师',
      images: selectedImages,
      likes: 0,
      comments: 0
    };

    setActivities(prev => [newActivity, ...prev]);
    setActivityDialogOpen(false);
    setSelectedImages([]);
    setActivityForm({ title: '', content: '' });

    toast({
      title: "活动发布成功",
      description: "活动已成功发布到班级动态",
    });
  };

  // 发布通知
  const handlePublishNotice = () => {
    if (!noticeForm.title || !noticeForm.content || !noticeForm.type) {
      toast({
        title: "请完善通知信息",
        description: "标题、内容和类型都是必填项",
        variant: "destructive"
      });
      return;
    }

    const newNotice = {
      id: notices.length + 1,
      title: noticeForm.title,
      content: noticeForm.content,
      type: noticeForm.type,
      date: new Date().toISOString().split('T')[0],
      author: '王老师',
      important: noticeForm.important
    };

    setNotices(prev => [newNotice, ...prev]);
    setNoticeDialogOpen(false);
    setNoticeForm({ title: '', content: '', type: '', important: false });

    toast({
      title: "通知发布成功",
      description: "通知已成功发布到班级公告",
    });
  };

  return (
    <FadeIn>
      <Toaster />
      <div className="container mx-auto py-6">
        <div className="flex justify-between items-center mb-6">
          <h1 className="text-2xl font-bold">班级动态</h1>
          <div className="flex space-x-2">
            <div className="relative">
              <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-500" />
              <Input
                type="search"
                placeholder="搜索动态..."
                className="pl-8 w-[200px] md:w-[300px]"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
            <Button variant="outline" size="icon">
              <Filter className="h-4 w-4" />
            </Button>
          </div>
        </div>
        
        {/* 选项卡 */}
        <Tabs value={activeTab} onValueChange={setActiveTab} className="mb-6">
          <div className="flex justify-between items-center mb-4">
            <TabsList>
              <TabsTrigger value="activities" className="flex items-center">
                <Calendar className="mr-2 h-4 w-4" />
                活动动态
              </TabsTrigger>
              <TabsTrigger value="notices" className="flex items-center">
                <Bell className="mr-2 h-4 w-4" />
                通知公告
              </TabsTrigger>
            </TabsList>
            
            {isTeacher && (
              <div>
                {activeTab === 'activities' ? (
                  <Dialog open={activityDialogOpen} onOpenChange={setActivityDialogOpen}>
                    <DialogTrigger asChild>
                      <Button className="flex items-center">
                        <Plus className="mr-2 h-4 w-4" />
                        发布活动
                      </Button>
                    </DialogTrigger>
                    <DialogContent className="sm:max-w-[600px]">
                      <DialogHeader>
                        <DialogTitle>发布班级活动</DialogTitle>
                        <DialogDescription>
                          分享班级活动照片和内容，记录美好时刻
                        </DialogDescription>
                      </DialogHeader>
                      <div className="grid gap-4 py-4">
                        <div className="grid gap-2">
                          <Label htmlFor="activity-title">活动标题</Label>
                          <Input 
                            id="activity-title" 
                            placeholder="请输入活动标题" 
                            value={activityForm.title}
                            onChange={(e) => handleActivityFormChange('title', e.target.value)}
                          />
                        </div>
                        <div className="grid gap-2">
                          <Label htmlFor="activity-content">活动内容</Label>
                          <Textarea 
                            id="activity-content" 
                            placeholder="请描述活动内容..." 
                            className="min-h-[120px]"
                            value={activityForm.content}
                            onChange={(e) => handleActivityFormChange('content', e.target.value)}
                          />
                        </div>
                        <div className="grid gap-2">
                          <Label>活动照片</Label>
                          <div className="flex flex-wrap gap-2">
                            {selectedImages.map((img, index) => (
                              <div key={index} className="relative w-24 h-24 rounded-md overflow-hidden">
                                <img 
                                  src={mockImageUrls[img as keyof typeof mockImageUrls]} 
                                  alt={`活动照片${index + 1}`}
                                  className="w-full h-full object-cover"
                                />
                              </div>
                            ))}
                            <Button 
                              variant="outline" 
                              className="w-24 h-24 flex flex-col items-center justify-center border-dashed"
                              onClick={handleImageSelect}
                            >
                              <ImageIcon className="h-8 w-8 text-gray-400" />
                              <span className="text-xs mt-1">添加照片</span>
                            </Button>
                          </div>
                        </div>
                      </div>
                      <DialogFooter>
                        <Button variant="outline" onClick={() => setActivityDialogOpen(false)}>取消</Button>
                        <Button onClick={handlePublishActivity}>发布活动</Button>
                      </DialogFooter>
                    </DialogContent>
                  </Dialog>
                ) : (
                  <Dialog open={noticeDialogOpen} onOpenChange={setNoticeDialogOpen}>
                    <DialogTrigger asChild>
                      <Button className="flex items-center">
                        <Plus className="mr-2 h-4 w-4" />
                        发布通知
                      </Button>
                    </DialogTrigger>
                    <DialogContent className="sm:max-w-[600px]">
                      <DialogHeader>
                        <DialogTitle>发布班级通知</DialogTitle>
                        <DialogDescription>
                          发布班级通知或公告，及时传达重要信息
                        </DialogDescription>
                      </DialogHeader>
                      <div className="grid gap-4 py-4">
                        <div className="grid gap-2">
                          <Label htmlFor="notice-title">通知标题</Label>
                          <Input 
                            id="notice-title" 
                            placeholder="请输入通知标题" 
                            value={noticeForm.title}
                            onChange={(e) => handleNoticeFormChange('title', e.target.value)}
                          />
                        </div>
                        <div className="grid gap-2">
                          <Label htmlFor="notice-type">通知类型</Label>
                          <Select value={noticeForm.type} onValueChange={(value) => handleNoticeFormChange('type', value)}>
                            <SelectTrigger>
                              <SelectValue placeholder="选择通知类型" />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="考试通知">考试通知</SelectItem>
                              <SelectItem value="家长通知">家长通知</SelectItem>
                              <SelectItem value="学习资料">学习资料</SelectItem>
                              <SelectItem value="日常通知">日常通知</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>
                        <div className="grid gap-2">
                          <Label htmlFor="notice-content">通知内容</Label>
                          <Textarea 
                            id="notice-content" 
                            placeholder="请输入通知内容..." 
                            className="min-h-[120px]"
                            value={noticeForm.content}
                            onChange={(e) => handleNoticeFormChange('content', e.target.value)}
                          />
                        </div>
                        <div className="flex items-center space-x-2">
                          <input 
                            type="checkbox" 
                            id="important" 
                            className="rounded text-primary"
                            checked={noticeForm.important}
                            onChange={(e) => handleNoticeFormChange('important', e.target.checked)}
                          />
                          <Label htmlFor="important" className="text-sm font-normal">标记为重要通知</Label>
                        </div>
                      </div>
                      <DialogFooter>
                        <Button variant="outline" onClick={() => setNoticeDialogOpen(false)}>取消</Button>
                        <Button onClick={handlePublishNotice}>发布通知</Button>
                      </DialogFooter>
                    </DialogContent>
                  </Dialog>
                )}
              </div>
            )}
          </div>
          
          {/* 活动动态选项卡 */}
          <TabsContent value="activities">
            <div className="space-y-6">
              {activities.map((activity) => (
                <Card key={activity.id} className="overflow-hidden">
                  <CardHeader className="pb-3">
                    <div className="flex justify-between items-start">
                      <div className="flex items-center space-x-3">
                        <Avatar>
                          <AvatarImage src="/avatars/teacher.png" alt={activity.author} />
                          <AvatarFallback>{activity.author[0]}</AvatarFallback>
                        </Avatar>
                        <div>
                          <CardTitle className="text-lg">{activity.title}</CardTitle>
                          <CardDescription>
                            {activity.author} · {activity.date}
                          </CardDescription>
                        </div>
                      </div>
                      <Button variant="ghost" size="icon">
                        <MoreHorizontal className="h-5 w-5" />
                      </Button>
                    </div>
                  </CardHeader>
                  <CardContent>
                    <p className="text-gray-700 mb-4">{activity.content}</p>
                    
                    {/* 图片展示 */}
                    <div className={`grid gap-2 ${
                      activity.images.length === 1 ? 'grid-cols-1' : 
                      activity.images.length === 2 ? 'grid-cols-2' : 
                      'grid-cols-3'
                    }`}>
                      {activity.images.map((img, index) => (
                        <div 
                          key={index} 
                          className={`rounded-lg overflow-hidden ${
                            activity.images.length === 1 ? 'max-h-[400px]' : 
                            activity.images.length === 2 ? 'max-h-[300px]' : 
                            'max-h-[200px]'
                          }`}
                        >
                          <img 
                            src={mockImageUrls[img as keyof typeof mockImageUrls]} 
                            alt={`活动照片${index + 1}`}
                            className="w-full h-full object-cover"
                          />
                        </div>
                      ))}
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          </TabsContent>
          
          {/* 通知公告选项卡 */}
          <TabsContent value="notices">
            <div className="space-y-4">
              {notices.map((notice) => (
                <Card key={notice.id} className={notice.important ? 'border-red-300 bg-red-50' : ''}>
                  <CardHeader className="pb-2">
                    <div className="flex justify-between items-start">
                      <div>
                        <div className="flex items-center space-x-2">
                          <CardTitle className="text-lg">{notice.title}</CardTitle>
                          {notice.important && (
                            <Badge variant="destructive" className="font-medium">重要</Badge>
                          )}
                        </div>
                        <CardDescription>
                          {notice.author} · {notice.date}
                        </CardDescription>
                      </div>
                      <Badge variant="outline">{notice.type}</Badge>
                    </div>
                  </CardHeader>
                  <CardContent>
                    <p className="text-gray-700">{notice.content}</p>
                  </CardContent>
                </Card>
              ))}
            </div>
          </TabsContent>
        </Tabs>
      </div>
    </FadeIn>
  );
}
